import { addCartListAPI, deleCartListAPI, getCartBySkuIdAPI, getCartListAPI, postMemberCartMergeAPI, putMemberCartAPI, putMemberCartBySkuIdAPI } from "@/api/cart";
import { CartItem } from "@/types/cart";
import { defineStore } from "pinia";
import useStore from "@/store";

export default defineStore('cart', {
  state: () => ({
    // 购物车列表
    list: [] as CartItem[],
  }),

  getters: {
    // 🔑登录状态
    isLogin (): boolean {
      const { userStore } = useStore()
      return !!userStore.profile.token
    },
    // 计算有效商品列表
    effectiveList (): CartItem[] {
      return this.list.filter(item => item.isEffective && item.stock > 0)
    },
    // 有效商品总数量 把effctiveList中的每一项的count叠加起来
    effectiveListCounts (): number {
      return this.effectiveList.reduce((pre, cur) => pre + cur.count, 0)
    },
    // 总钱数  = 所有单项的钱数累加  单项的钱数 = 数量 * 单价
    effectiveListPrice (): string {
      return this.effectiveList.reduce((pre, cur) => pre + (cur.count * +cur.nowPrice), 0).toFixed(2)
    },
    // 已选择的列表
    selectedList (): CartItem[] {
      return this.effectiveList.filter((item) => item.selected)
    },
    // 已选择的商品总数
    selectedListCounts (): number {
      return this.selectedList.reduce((sum, item) => sum + item.count, 0)
    },
    // 已选择的列表总价
    selectedListPrice (): string {
      return this.selectedList
        .reduce((sum, item) => sum + item.count * Number(item.nowPrice), 0)
        .toFixed(2)
    },

    // 是否全选
    isAllSelected (): boolean {
      return this.effectiveList.every(item => item.selected) && this.effectiveList.length > 0
    },
  },

  actions: {
    // 加入购物车
    async addCartList (data: CartItem) {
      if (this.isLogin) {
        await addCartListAPI({
          skuId: data.skuId,
          count: data.count,
        })
        // 重新获取购物车数据
        this.getCartList()
      } else {
        // 1. 判断购物车列表中是否有该商品数据
        const goods = this.list.find((item) => item.skuId === data.skuId)
        if (goods) {
          // 2. 如果商品存在，直接把数量加起来
          goods.count += data.count
        } else {
          // 3. 如果商品不存在，直接添加该商品
          this.list.unshift(data)
        }
      }
    },
    // 获取购物车列表
    async getCartList () {
      if (this.isLogin) {
        const res = await getCartListAPI()
        this.list = res.data.result
      } else {
        // 遍历发送请求, 校验更新sku商品的库存和价格, 是否有效
        this.list.forEach(async (cartItem) => {
          const { skuId } = cartItem
          // 根据 skuId 获取最新商品信息
          const res = await getCartBySkuIdAPI(skuId)
          // 保存最新商品信息
          const lastCartInfo = res.data.result
          // 更新商品现价
          cartItem.nowPrice = lastCartInfo.nowPrice
          // 更新商品库存
          cartItem.stock = lastCartInfo.stock
          // 更新商品是否有效
          cartItem.isEffective = lastCartInfo.isEffective
        })
      }
    },

    // 删除购物车商品
    async deleteCart (ids: string[]) {
      if (this.isLogin) {
        await deleCartListAPI(ids)
        // 重新获取购物车数据
        this.getCartList()
      } else {
        this.list = this.list.filter(item => !ids.includes(item.skuId))
      }
    },

    // 修改购物车状态
    async updatedCart (skuId: string, data: { selected?: boolean, count?: number }) {
      if (this.isLogin) {
        await putMemberCartBySkuIdAPI(skuId, data)
        // 重新获取购物车数据
        this.getCartList()
      } else {
        const goods = this.list.find(item => item.skuId === skuId)
        // 修改选择状态
        if (data.selected !== undefined) {
          goods!.selected = data.selected
        }
        // 修改数量
        if (data.count !== undefined) {
          goods!.count = data.count
        }
      }
    },
    // 修改是否全选
    async updateCartAllSelected (isSelected: boolean) {
      if (this.isLogin) {
        await putMemberCartAPI(isSelected)
        // 重新获取购物车数据
        this.getCartList()
      } else {
        this.list.forEach(item => {
          item.selected = isSelected
        })
      }
    },

    // 清空购物车
    clearCart () {
      this.list = []
    },

    // 合并购物车
    async mergeLocalCart () {
      const data = this.list.map(({ skuId, selected, count }) => ({
        skuId,
        selected,
        count
      }))
      await postMemberCartMergeAPI(data)
      // 合并成功，重新获取购物车列表
      this.getCartList()
    }
  },
  persist: {
    key: 'cart', //存储名称
    storage: localStorage, // 存储方式
    paths: ['list'], //指定 state 中哪些数据需要被持久化。[] 表示不持久化任何状态，undefined 或 null 表示持久化整个 state
  } as {}
})